package com.ok.es.listener;

import cn.hutool.json.JSONUtil;
import com.ok.common.domain.po.CardDoc;
import com.ok.common.domain.po.CartoonDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName CardEsListener
 * @Description 帖子消息队列数据同步更新
 * @Author hw
 * @Date 2024/5/15 23:21
 */
@Slf4j
@Component
public class CardEsListener {
    @Autowired
    private RestHighLevelClient client;
    /*
    添加帖子
     */
    @RabbitListener(queues = "card_add_queue")
    public void listenerCardAdd(CardDoc cardDoc) throws IOException {
        log.info("es接收帖子信息："+cardDoc);

        //将cartoonDoc转换为JSON文档
        String doc = JSONUtil.toJsonStr(cardDoc);
        IndexRequest request = new IndexRequest("card").id(String.valueOf(cardDoc.getId()));

        //准备JSON文档
        request.source(doc, XContentType.JSON);
        //发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    /*
    删除帖子
    */
    @RabbitListener(queues = "card_rm_queue")
    public void rm(Long ids) throws IOException {
        log.info("漫画es--id:{}",ids);
        // 1.准备Request，两个参数，第一个是索引库名，第二个是文档id
        DeleteRequest request = new DeleteRequest("card", String.valueOf(ids));
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }
}
